<?php

class Account extends MY_Controller
{
	const MAX_LOGIN_ATTEMPTS = 5;
	
	function Account()
	{
		parent::MY_Controller();

		header('Expires: Thu, 01-Jan-70 00:00:01 GMT');
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Pragma: no-cache');
		
		# add custom css file for user controller
		$this->data['header_data']['css'][] = '/css/account.css';
		$this->data['header_data']['css'][] = '/css/home.css';
		$this->data['header_data']['js'][] = '/js/jquery/jquery-1.4.3.min.js';
		$this->data['header_data']['js'][] = '/js/tmp.js';
		$this->data['header_data']['js'][] = '/js/account.js';
		
		$this->lang->load('account');
	}	


	public function create()
	{
		
		# default title in case controller does not specify particular title
		$this->data['header_data']['page_title'] = 'turbotask.me - ' . lang('create_account');

		$this->load->helper('security');
		$this->load->library('form_validation');
		$this->load->model('Account_model', 'account');
		
		if($this->input->post('submit'))
		{
			# anti robot/automaton checker
			if( (int)$this->input->post('tmp') < 3 )
			{
				redirect( site_url('account/create'), 'location' );
				die;
			}
			
			// first check if the nonce is correct
			$nonce = $this->input->xss_clean($this->input->post('nonce'));
			if($nonce !== $this->session->userdata('registration_nonce'))
			{
				$this->load->helper('cookie');
				if( !get_cookie('tt_me') ) 
				{
					redirect( site_url('service/cookies'), 'location' );	
				}
				else
				{					
					redirect( site_url('account/create'), 'location' );	
				}
				die;
			}
			
			$this->form_validation->set_rules('email', lang('email'), 'trim|required|valid_email|callback__isUniqueEmail');
			$this->form_validation->set_rules('password', lang('password'), 'trim|required|min_length[6]');
			$this->form_validation->set_rules('password2', lang('confirm_password'), 'trim|required|matches[password]');
			//$this->form_validation->set_rules('personname', lang('name'), 'trim');
			
			if($this->form_validation->run() == FALSE)
			{
				# create new nonce
				$viewdata['nonce'] = $this->createNonce('registration', true);
				$this->data['content'] = $this->load->view('account/create', $viewdata, true);
			}
			else 
			{
				$user = array();
				$user['email'] = $this->input->post('email');
				$user['salt'] = substr(md5(uniqid(rand(), true)), 0, 16);
				$user['password'] = hash_hmac( 'sha512', $this->input->post('password') . $user['salt'], GLOBAL_USER_KEY );
				//$user['name'] = $this->input->xss_clean( $this->input->post('personname') );
				$user['ip'] = $this->input->ip_address();
				
				if( $user_id = $this->account->create($user) )
				{
					# we don't need these anymore
					unset($user['password']);
					unset($user['salt']);
					$this->session->unset_userdata('registration_nonce');
					
					$this->session->set_userdata('user_id', $user_id);
					$this->session->set_userdata('email', $user['email']);
					$this->session->set_userdata('tz', 'UP2'); # default time zone is GMT+02:00 Eastern Europe
					//$this->session->set_userdata('name', $user['name']);
					
					# send registration email (confirm email ownership??? TO-DO later if problems happen)
					//$this->sendRegistrationEmail($user['email']);
					
					redirect( site_url('tasks'), 'location');
				}
				else
				{
					$viewdata['title'] = lang('create_account');
					$viewdata['message'] = lang('err_create_account') . $this->config->item('support_email');
					$this->data['content'] = $this->load->view('account/error', $viewdata, true);
				}
			}
		}
		else
		{
			$viewdata['nonce'] = $this->createNonce('registration', true);
			$this->data['content'] = $this->load->view('account/create', $viewdata, true);
		}
		
		$this->data['no_sidebar'] = true;
		$this->load->view('global/master-view', $this->data);
	}


	/*
	 * This method handles normal login via the login form on the Home screen
	 */
	public function login()
	{
		# if user is logged-in
		if($this->session->userdata('user_id') > 0)
			redirect( site_url('tasks'), 'location');

		# set where to redirect on successfull or unsuccessfull login
		$redirect_url = $this->input->xss_clean($this->input->post('redirect_url'));
		$redirect_url = !empty($redirect_url) ? $redirect_url : '/';

		# user_agent is used in the view, to display unsupported browsers
		$this->load->library('user_agent');
		$this->load->helper('security');
		$this->load->library('form_validation');
		
		if($this->input->post('login'))
		{
			# check if the user has cookies enabled
			$this->load->helper('cookie');
			if( !get_cookie('tt_me') )
			{
				redirect( site_url('service/cookies'), 'location' );	
			}
			
			# if the user has made a lot of incorrect retries to login, redirect him to start over
			if((int)$this->session->userdata('login_retries') > self::MAX_LOGIN_ATTEMPTS)
			{
				$this->session->set_userdata('login_retries', 1);
				redirect( site_url($redirect_url), 'location' );
			}
			
			# first check if the nonce is correct
			$nonce = $this->input->xss_clean($this->input->post('nonce'));
			if($nonce !== $this->session->userdata('login_nonce') && (int)$this->session->userdata('login_retries') > 0)
			{
				redirect( site_url($redirect_url), 'location' );				
			}			
			else
			{
				$this->load->model('Account_model', 'account');

				$email = $this->input->post('email'); # no need for xss clean, because it's valid email address
				
				# get user info to check if credentials are correct
				$userinfo = $this->account->login($email);
				
				# create a has from the user's submitted password
				$hashed_pass = hash_hmac( 'sha512', $this->input->post('password') . @$userinfo->salt, GLOBAL_USER_KEY );
				
				if(!$userinfo || $hashed_pass !== $userinfo->password)
				{
					# increment retries counter by 1 each time the user does not sign in correctly
					$login_retries = (int)$this->session->userdata('login_retries') + 1;
					$this->session->set_userdata( 'login_retries', $login_retries );
					$viewdata['nonce'] = $this->createNonce('login', true);
					$viewdata['login_message'] = lang('err_login');
					
					# hack to check if login is via oauth or normal ?!
					if(!isset($redirect_url) || strpos($redirect_url, 'oauth') !== false)
					{	
						$redirect_url .= '&invalid';
						redirect( site_url($redirect_url), 'location' );
					}
					else
					{
						$this->data['content'] = $this->load->view('home-login', $viewdata, true);						
					}
				}
				else
				{
					# set user remember me cookie in case she selected the option
					if($this->input->post('rememberme'))
					{
						# create remember me token
						if( $token = $this->account->rememberUser($userinfo->user_id, $userinfo->email) )
						{
							# encrypt the cookie value
							$this->load->library('encrypt');
							$cookie = $this->encrypt->encode( $userinfo->email . '-' . $token->series . '-' . $token->value );
							setcookie('usr', $cookie, time() + THREE_MONTHS, '/', $this->config->item('cookie_domain'), 0, true);
							
							$this->session->set_userdata('token', $token->value);
							$this->session->set_userdata('series', $token->series);
						}
					}
					
					# login ok
					$this->account->updateLastLogin($userinfo->user_id, $this->input->ip_address());
					
					# temporary hack to enable only my user to be admin
					if( (int)$userinfo->user_id === 1 ){
						$this->session->set_userdata('admin', 1);
					}
					
					# clean orphaned tags each time a user logs in
					$this->load->model('Tasks_model', 'tasks');
					$this->tasks->clearOrphanedTags();

					$this->session->set_userdata('user_id', $userinfo->user_id);
					$this->session->set_userdata('email', $userinfo->email);
					//$this->session->set_userdata('name', $userinfo->name);
					$this->session->set_userdata('tz', $userinfo->timezone);
					
					# when user has logged-in the normal way (not with persistant login cookie), he can access
					# his operations like change password and other secure actions
					$this->session->set_userdata('superuser', true);
					
					# remove from session login nonce
					$this->session->unset_userdata('login_nonce');
					//$this->session->unset_userdata('access_settings');
					
					redirect( site_url($redirect_url), 'location');					
				}
			}
			
			$this->load->view('global/master-view', $this->data);
		}
		else
		{
			redirect( site_url('/'), 'location');
		}
	}
	


	public function logout($everywhere = false)
	{
		if($this->session->userdata('user_id') > 0)
		{
			$email = $this->session->userdata('email');
			$token = $this->session->userdata('token');
			$series = $this->session->userdata('series');
			
			$this->load->model('Account_model', 'account');
			$this->account->unrememberUser($email, $token);
			
			# remove user cookie
			$this->load->library('encrypt');
			$cookie = $this->encrypt->encode( $email . '-' . $series . '-' . $token );
			setcookie('usr', $cookie, time() - 3600, '/', $this->config->item('cookie_domain'), 0, true);			
			
			$this->session->sess_destroy();
			
			redirect( site_url('account/logout'), 'location');
		}
		else
		{
			# create new nonce for the login form
			$viewdata['nonce'] = $this->createNonce('login');
			$this->data['content'] = $this->load->view('account/logout', $viewdata, true);
			$this->data['no_sidebar'] = true;
			$this->load->view('global/master-view', $this->data);
		}
	}



	public function recover()
	{
		# if user is logged-in
		if($this->session->userdata('user_id') > 0) redirect( site_url('tasks'), 'location');
		
		# default title in case controller does not specify particular title
		$this->data['header_data']['page_title'] = 'turbotask.me - ' . lang('recover_password');
		
		$this->load->library('form_validation');
		$this->load->model('Account_model', 'account');
		
		if($this->input->post('submit'))
		{
			# anti robot/automaton checker
			if( (int)$this->input->post('tmp') < 1 )
			{
				redirect( site_url('account/recover'), 'location' );
				die;
			}

			// first check if the nonce is correct
			$nonce = $this->input->xss_clean($this->input->post('nonce'));
			if($nonce !== $this->session->userdata('recover_nonce'))
			{
				$this->load->helper('cookie');
				if( !get_cookie('tt_me') ) 
				{
					redirect( site_url('service/cookies'), 'location' );	
				}
				else
				{					
					redirect( site_url('account/recover'), 'location' );	
				}
				die;
			}

			$this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email|callback__isExistingEmail');
			
			if($this->form_validation->run() == FALSE)
			{
				# create new nonce
				$viewdata['nonce'] = $this->createNonce('recover', true);
				$this->data['content'] = $this->load->view('account/recover', $viewdata, true);
			}
			else
			{
				# remove from session recover_nonce, we don't need it anymore
				$this->session->unset_userdata('recover_nonce');
				
				$viewdata['title'] = lang('recover_password');
				
				$email = $this->input->post('email'); # no need for XSS clean because it's valid email address
				$key = $this->account->createRecoveryKey( $email );
				
				if(!$key)
				{
					redirect( site_url('status/code') . '/' . GENERAL_ERROR, 'location');
				}
				else
				{
					if($this->_sendRecoveryKey($email, $key) == TRUE)
					{
						redirect( site_url('status/code') . '/' . OK_RECOVERY_KEY_SENT, 'location');
					}
					else
					{
						redirect( site_url('status/code') . '/' . GENERAL_ERROR, 'location');
					}
				}
			}
		}
		else
		{
			$viewdata['nonce'] = $this->createNonce('recover', true);
			$this->data['content'] = $this->load->view('account/recover', $viewdata, true);
		}
		
		$this->data['no_sidebar'] = true;
		$this->load->view('global/master-view', $this->data);				
	}



	private function createNonce($type = null, $strong = false)
	{
		$nonce = md5(uniqid(rand(), $strong));	
		switch($type)
		{
			case 'registration':
				$this->session->set_userdata('registration_nonce', $nonce);
				break;
				
			case 'login':
				$this->session->set_userdata('login_nonce', $nonce);
				break;
				
			case 'recover':
				$this->session->set_userdata('recover_nonce', $nonce);
				break;
				
			case 'newpass':
				$this->session->set_userdata('newpass_nonce', $nonce);
				break;
				
			case 'profile':
				$this->session->set_userdata('profile_nonce', $nonce);
				break;
				
			case 'password':
				$this->session->set_userdata('password_nonce', $nonce);
				break;
				
			case 'remove':			
				$this->session->set_userdata('remove_nonce', $nonce);
				break;
		}
		return $nonce;
	}



	public function newpass($key = null)
	{
		# if user is logged-in
		if($this->session->userdata('user_id') > 0) redirect( site_url('tasks'), 'location');

		$this->data['header_data']['page_title'] = 'turbotask.me - ' . lang('recover_password');
		
		$this->load->helper('security');
		$this->load->library('form_validation');
		$this->load->model('Account_model', 'account');
		
		if($this->input->post('submit') && $this->session->userdata('validation_key') == TRUE)
		{
			# anti robot/automaton checker
			if( (int)$this->input->post('tmp') < 3 )
			{
				header('HTTP/1.1 400 Bad Request');
				header('Connection:close');
				echo 'Invalid request.';
				exit(0);				
			}

			// first check if the nonce is correct
			$nonce = $this->input->xss_clean($this->input->post('nonce'));
			if($nonce !== $this->session->userdata('newpass_nonce'))
			{
				$this->load->helper('cookie');
				if( !get_cookie('tt_me') ) 
				{
					redirect( site_url('service/cookies'), 'location' );	
				}
				else
				{
					redirect( site_url('status/code') . '/' . GENERAL_ERROR, 'location' );	
				}
				die;
			}

			$this->form_validation->set_rules('email', lang('email'), 'required|valid_email|callback__checkNewPassEmail');
			$this->form_validation->set_rules('password', lang('password'), 'required|min_length[6]');
			$this->form_validation->set_rules('password2', lang('confirm_password'), 'required|matches[password]');
			
			if($this->form_validation->run() == FALSE)
			{
				# create new nonce
				$viewdata['recovery_key'] = $key;
				$viewdata['nonce'] = $this->createNonce('newpass', true);
				$this->data['content'] = $this->load->view('account/newpass', $viewdata, true);
			}
			else 
			{
				$user = array();
				$user['email'] = $this->session->userdata('email');
				$user['salt'] = substr(md5(uniqid(rand(), true)), 0, 16);
				$user['newpass'] = hash_hmac( 'sha512', $this->input->post('password') . $user['salt'], GLOBAL_USER_KEY );
				if($this->account->changePass($user))
				{
					redirect( site_url('status/code') . '/' . OK_CHANGE_PASS, 'location');
				}
				else 
				{
					redirect( site_url('status/code') . '/' . ERR_CHANGE_PASS, 'location');
				}
			}
		}
		else
		{
			if($email = $this->account->checkRecoveryKey($key)) 
			{
				$viewdata['nonce'] = $this->createNonce('newpass', true);
				
				# save in the session that the user has valid recovery key
				$this->session->set_userdata('validation_key', true);
				$this->session->set_userdata('email', $email);
				$this->data['content'] = $this->load->view('account/newpass', $viewdata, true);
			}
			else
			{
				$viewdata['title'] = lang('recover_password');
				$viewdata['message'] = lang('invalid_key');
				$this->data['content'] = $this->load->view('account/error', $viewdata, true);	
			}		
		}
		
		$this->load->view('global/master-view', $this->data);
	}

	
	/*
	 * Check if the submitted email by the user is the same as the email with which the recovery key
	 * is associated. If not, increment bad retries counter and if passed certain amount of retries
	 * invalidate the whole recovery process.
	 */
	function _checkNewPassEmail($email)
	{
		if( $email !== $this->session->userdata('email') )
		{
			$retries = (int)$this->session->userdata('newpass_retries');
			$retries++;
			if($retries > 4)
			{
				$this->account->invalidateUserRecover($this->session->userdata('email'));
				$this->session->sess_destroy();
				redirect( site_url('status/code') . '/' . ERR_TOO_MANY_RECOVERY_ATTEMPTS, 'location' );
				die;
			}
			$this->session->set_userdata('newpass_retries', $retries);
			
			$this->form_validation->set_message('_checkNewPassEmail', lang('invalid_email'));
			return FALSE;
		}
		
		return TRUE; # validation is ok
	}

	
	/*
	 * Check if email is existing in the database.
	 */
	function _isUniqueEmail($email)
	{
		if($this->account->isUniqueEmail($email) == FALSE)
		{
			$this->form_validation->set_message('_isUniqueEmail', lang('already_registered'));
			return FALSE;
		}
		
		return TRUE; # validation is OK, email is unique
	}
	
	
	
	function _isExistingEmail($email)
	{
		if($this->account->isUniqueEmail($email) == TRUE)
		{
			$this->form_validation->set_message('_isExistingEmail', lang('email_not_exist'));
			return FALSE;
		}
		
		return TRUE; # validation is OK, email is existing
	}	
	
	
	
	private function _sendRecoveryKey($email, $key)
	{
		$headers  = "From: turbotask.me <noreply@turbotask.me>\r\n";
		$headers .= "Reply-To: support@turbotask.me\r\n";
		$headers .= "Return-Path: support@turbotask.me\r\n";
		$headers .= 'MIME-Version: 1.0' . "\n";
		$headers .= 'Content-type: text/plain; charset=utf-8' . "\r\n";
		
		$subject = lang('recover_pass_subject');
		
		$message = lang('recover_email_message_1');
		$message .= site_url('account/newpass') . '/' . $key;
		$message .= lang('recover_email_message_2');

		//echo '<pre>';echo $message; die;
		//return TRUE;
		
		return mail($email, $subject, $message, $headers);
	}



	public function settings($action = 'profile')
	{
		$user_id = (int)$this->session->userdata('user_id');
		if($user_id == 0) redirect( site_url('/'), 'location');
		
		/*
		# if user is logged-in with persistent cookie ONLY, ask him to enter password
		if($this->session->userdata('super_user') == false)
		{
			$this->session->set_userdata('access_settings', true);
			
		}
		*/
			
		switch($action)
		{
			case 'profile':
				$this->_settingsProfile($user_id);
				break;
				
			case 'password':
				$this->_settingsPassword($user_id);
				break;
				
			case 'remove':
				$this->_removeAccount($user_id);
				break;	
				
			case 'logout':
				if(IS_AJAX)
				{
					ob_end_clean();
					$this->load->model('Account_model', 'account');
					$this->account->unrememberUserEverywhere($this->session->userdata('email'));
					die;
				}
				break;
		}
	}
	
	
	private function _settingsProfile($user_id)
	{
		$this->data['header_data']['page_title'] = 'turbotask.me - ' . lang('profile');

		$this->load->library('form_validation');
		$this->load->model('Account_model', 'account');

		$profile = $this->account->get($user_id);
		$viewdata['tz'] = $profile->timezone;
		$viewdata['name'] = $profile->name; 
		
		if($this->input->post('submit'))
		{
			// first check if the nonce is correct
			$nonce = $this->input->xss_clean($this->input->post('nonce'));
			if($nonce !== $this->session->userdata('profile_nonce'))
			{
				$this->load->helper('cookie');
				if( !get_cookie('tt_me')) 
				{
					redirect( site_url('service/cookies'), 'location' );	
				}
				else
				{					
					redirect( site_url('account/settings/profile'), 'location' );	
				}
				die;
			}
			
			$this->form_validation->set_rules('email', lang('email'), 'trim|required|valid_email|callback__checkNewEmail');
			
			if($this->form_validation->run() == FALSE)
			{
				# create new nonce
				$viewdata['nonce'] = $this->createNonce('profile', true);
				$this->data['content'] = $this->load->view('account/settings-profile', $viewdata, true);
			}
			else 
			{
				# save profile data
				$user['email'] = $this->session->userdata('email');
				$user['newemail'] = $this->input->post('email');
				$user['name'] = $this->input->xss_clean($this->input->post('username'));
				$user['tz'] = $this->input->xss_clean($this->input->post('timezones'));
				
				$result = $this->account->saveProfile($user_id, $user);
				if($result->status === 0)
				{
					$this->session->set_userdata('tz', $user['tz']);
					
					# send confirmation email for change of email
					if(isset($result->key) && !empty($result->key))
					{
						$this->_sendEmailConfirmationKey($user['newemail'], $result->key);
					}
					
					$viewdata['tz'] = $user['tz'];
					$viewdata['name'] = $user['name'];
					$viewdata['message'] = lang('profile_saved');
				}
				else
				{
					$viewdata['message'] = lang('err_profile_save');
				}
				$viewdata['nonce'] = $this->createNonce('profile', true);	
				$this->data['content'] = $this->load->view('account/settings-profile', $viewdata, true);			
			}			
		}
		else
		{
			$viewdata['nonce'] = $this->createNonce('profile', true);	
			$this->data['content'] = $this->load->view('account/settings-profile', $viewdata, true);		
		}
		
		$this->data['no_sidebar'] = true;
		$this->load->view('global/master-view', $this->data);
	}

	
	function _checkNewEmail($email)
	{
		log_message('info', __METHOD__ . ' started...');
		
		# if user does not change her email
		if($email === $this->session->userdata('email'))
		{
			log_message('info', __METHOD__ . ' user did not change his email ');
			return TRUE;
		}
		
		if($this->account->isUniqueEmail($email) == FALSE)
		{
			log_message('info', 'isUniqueEmail == false');
			$this->form_validation->set_message('_checkNewEmail', lang('already_registered'));
			return FALSE;
		}
		
		log_message('info', __METHOD__ . ' new email is ok ');
		return TRUE; # validation is OK, email is unique		
	}

	
	public function newemail($key = null)
	{	
		$this->load->helper('security');
		$this->load->model('Account_model', 'account');

		if(!$key && !$this->account->checkConfirmEmailKey) redirect( site_url('/'), 'location');
		
		$key = xss_clean($key);
		if($new_email = $this->account->changeEmail($key))
		{
			$this->session->set_userdata('email', $new_email);
			redirect( site_url('status/code') . '/' . OK_CHANGE_EMAIL, 'location');			
		}
		else
		{
			redirect( site_url('status/code') . '/' . GENERAL_ERROR, 'location');			
		}
	}
	

	private function _sendEmailConfirmationKey($email, $key)
	{
		$headers  = "From: turbotask.me <noreply@turbotask.me>\r\n";
		$headers .= "Reply-To: support@turbotask.me\r\n";
		$headers .= "Return-Path: support@turbotask.me\r\n";
		$headers .= 'MIME-Version: 1.0' . "\n";
		$headers .= 'Content-type: text/plain; charset=utf-8' . "\r\n";
		
		$subject = lang('confirm_email_subject');
		
		$message = lang('confirm_email_message_1');
		$message .= site_url('account/newemail') . '/' . $key;
		$message .= lang('confirm_email_message_2');

		//echo '<pre>';echo $message; die;
		//return TRUE;
		
		return mail($email, $subject, $message, $headers);
	}
	
	
	private function _settingsPassword($user_id)
	{
		$this->data['header_data']['page_title'] = 'turbotask.me - ' . lang('change_pass');

		$this->load->library('form_validation');
		$this->load->model('Account_model', 'account');

		$profile = $this->account->get($user_id);
		
		if($this->input->post('submit'))
		{
			// first check if the nonce is correct
			$nonce = $this->input->xss_clean($this->input->post('nonce'));
			if($nonce !== $this->session->userdata('password_nonce'))
			{
				$this->load->helper('cookie');
				if( !get_cookie('tt_me')) 
				{
					redirect( site_url('service/cookies'), 'location' );	
				}
				else
				{					
					redirect( site_url('account/settings/password'), 'location' );	
				}
				die;
			}
			
			# create new nonce
			$viewdata['nonce'] = $this->createNonce('password', true);
		
			$this->form_validation->set_rules('currpass', lang('currpass'), 'trim|required|callback__checkCurrentPassword');
			$this->form_validation->set_rules('newpass', lang('newpass'), 'trim|required|min_length[6]');			
			$this->form_validation->set_rules('newpass2', lang('newpass2'), 'trim|required|matches[newpass]');			
			if($this->form_validation->run() == FALSE)
			{
				$this->data['content'] = $this->load->view('account/settings-password', $viewdata, true);
			}
			else 
			{
				# hash the new password and save it to db
				$user = array();
				$user['email'] = $this->session->userdata('email');
				$user['salt'] = substr(md5(uniqid(rand(), true)), 0, 16);
				$user['newpass'] = hash_hmac( 'sha512', $this->input->post('newpass') . $user['salt'], GLOBAL_USER_KEY );
				if($this->account->changePass($user))
				{
					$viewdata['message'] = lang('password_saved');
				}
				else
				{
					$viewdata['message'] = lang('password_err');
				}
				$this->data['content'] = $this->load->view('account/settings-password', $viewdata, true);
			}			
		}
		else
		{
			$viewdata['nonce'] = $this->createNonce('password', true);			
			$this->data['content'] = $this->load->view('account/settings-password', $viewdata, true);		
		}

		$this->data['no_sidebar'] = true;
		$this->load->view('global/master-view', $this->data);
	}
	
	
	function _checkCurrentPassword($password)
	{				
		if(!$user_id = $this->session->userdata('user_id')) return false;
				
		$userinfo = $this->account->get($user_id);
		
		$hashed_pass = hash_hmac( 'sha512', $password . @$userinfo->salt, GLOBAL_USER_KEY );
				
		if(!$userinfo || $hashed_pass !== $userinfo->password)
		{
			$this->form_validation->set_message('_checkCurrentPassword', lang('invalid_password'));
			return FALSE;
		}
		
		return TRUE;
	}
	
	
	private function _removeAccount($user_id)
	{
		$this->data['header_data']['page_title'] = 'turbotask.me - ' . lang('account_remove');

		if($this->input->post('submit'))
		{
			// first check if the nonce is correct
			$nonce = $this->input->xss_clean($this->input->post('nonce'));
			if($nonce !== $this->session->userdata('remove_nonce'))
			{
				$this->load->helper('cookie');
				if( !get_cookie('tt_me')) 
				{
					redirect( site_url('service/cookies'), 'location' );	
				}
				else
				{					
					redirect( site_url('account/settings/remove'), 'location' );	
				}
				die;
			}
			
			$this->load->model('Tasks_model', 'tasks');
			$this->load->model('Account_model', 'account');
			
			# check if password is valid
			$userinfo = $this->account->login($this->session->userdata('email'));
			
			# create a has from the user's submitted password
			$hashed_pass = hash_hmac( 'sha512', $this->input->post('currpass') . @$userinfo->salt, GLOBAL_USER_KEY );
			if(!$userinfo || $hashed_pass !== $userinfo->password)
			{
				$viewdata['message'] = $this->lang->line('invalid_password');
			}
			else
			{
				$this->tasks->removeUser($user_id);
				$this->account->remove($user_id, $this->session->userdata('email'));
				
				redirect( site_url('account/logout'), 'location');			
			}	
		}
		//echo '<pre>';var_dump($this->lang);
		
		$viewdata['nonce'] = $this->createNonce('remove', true);
		$this->data['content'] = $this->load->view('account/settings-remove', $viewdata, true);
		$this->data['no_sidebar'] = true;
		$this->load->view('global/master-view', $this->data);			
	}
	
	
	private function _settingsLogout($email)
	{
		$this->load->model('Account_model', 'account');
		$this->account->unrememberUserEverywhere($email);
		
		$viewdata['message'] = lang('logout_everywhere_ok');
		$viewdata['nonce'] = $this->createNonce('profile', true);	
		$this->data['content'] = $this->load->view('account/settings-profile', $viewdata, true);			
		$this->data['no_sidebar'] = true;
		$this->load->view('global/master-view', $this->data);
	}
	
}